package zhoug.player.core;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Log;
import android.view.TextureView;
import android.view.ViewGroup;

import zhoug.common.utils.AppUtils;
import zhoug.common.utils.BitmapUtils;
import zhoug.common.utils.ThreadUtils;
import zhoug.logging.Logger;
import zhoug.player.core.widget.VideoRatioTextureView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @Author: zhoug
 * @Date: 2023/1/11
 * @Description:
 */
public abstract class BasePlayer implements ZPlayer {
    private static final String TAG = ">>>BaseZPlayer";
    private static final boolean DEBUG= PlayerSDK2.isDebug();
    private static final boolean MUTE_DEF = true;//默认静音
    protected Context mContext;
    protected String mPlayUrl;
    protected String mTalkUrl;
    protected OnPlayListener mOnPlayListener;//播放监听
    protected OnCapturePictureListener mOnCapturePictureListener;//截图监听
    protected OnVideoRecordListener mOnVideoRecordListener;//录像监听
    protected OnPlayProgressListener mOnPlayProgressListener;//播放进度监听
    protected OnTalkListener mOnTalkListener;//对讲监听
    protected OnCameraAbilityCallback mOnCameraAbilityCallback;//设备能力集回掉
    protected OnCameraSettingCallback mOnCameraSettingCallback;//摄像头设置回掉
    protected TextureView mTextureView;
    protected ViewGroup mPlayViewGroup;
    protected boolean mMute = MUTE_DEF;//默认静音
    protected @State int mPlayState = STATE_IDLE;//播放状态
    protected int mRenderMode = RENDER_MODE_FULL_FILL_SCREEN;
    protected CameraAbility mCameraAbility;
    protected CameraSetting mCameraSetting;
    protected boolean mAutoGetAbility=false;
    protected boolean mAutoGetSettings=false;
    /**
     * 设置上下文
     *
     * @param context
     */
    @Override
    public void setContext(@NonNull Context context) {
        this.mContext = context;
    }

    /**
     * 设置播放url
     *
     * @param url
     */
    @Override
    public void setPlayUrl(@Nullable String url) {
        this.mPlayUrl = url;
    }

    /**
     * 获取播放地址
     *
     * @return
     */
    @Override
    public String getPlayUrl() {
        return mPlayUrl;
    }

    /**
     * 设置显示页面
     *
     * @param textureView
     */
    @Override
    public void setVideoTextureView(@Nullable TextureView textureView) {
        this.mTextureView = textureView;
    }

    /**
     * 设置PlayView容器
     *
     * @param viewGroup
     */
    @Override
    public void setPlayViewGroup(@Nullable ViewGroup viewGroup) {
        this.mPlayViewGroup=viewGroup;
    }

    /**
     * 设置播放渲染模式
     * 渲染模式有两种:
     * {@link #RENDER_MODE_FULL_FILL_SCREEN}平铺模式：视频画面将会按照比例铺满屏幕，多余部分会被裁减掉，此模式下不会有黑边。
     * {@link #RENDER_MODE_ADJUST_RESOLUTION}自适应模式：视频画面将等比例缩放，会居中显示，此模式可能会有黑边。
     *
     * @param renderMode {@link #RENDER_MODE_FULL_FILL_SCREEN,#RENDER_MODE_ADJUST_RESOLUTION}
     */
    @Override
    public void setRenderMode(int renderMode) {
        this.mRenderMode = renderMode;
        if (mTextureView instanceof VideoRatioTextureView) {
            ((VideoRatioTextureView) mTextureView).setRenderMode(renderMode);
        }
    }

    /**
     * 设置播放渲染模式
     *
     * @return
     */
    @Override
    public int getRenderMode() {
        return this.mRenderMode;
    }

    /**
     * 设置对讲url
     *
     * @param talkUrl
     */
    @Override
    public void setTalkUrl(String talkUrl) {
        this.mTalkUrl = talkUrl;
    }

    /**
     * 设置静音
     *
     * @param mute true:静音,false:非静音
     */
    @Override
    public void setMute(boolean mute) {
        this.mMute = mute;
    }

    /**
     * 是否是静音
     *
     * @return
     */
    @Override
    public boolean isMute() {
        return mMute;
    }

    /**
     * 播放监听
     *
     * @param onPlayListener
     */
    @Override
    public void setOnPlayListener(@Nullable OnPlayListener onPlayListener) {
        this.mOnPlayListener = onPlayListener;
    }

    /**
     * 设置截屏回掉
     *
     * @param onCapturePictureListener
     */
    @Override
    public void setOnCapturePictureListener(@Nullable OnCapturePictureListener onCapturePictureListener) {
        this.mOnCapturePictureListener = onCapturePictureListener;
    }

    /**
     * 设置视频录制回掉
     *
     * @param onVideoRecordListener
     */
    @Override
    public void setOnVideoRecordListener(@Nullable OnVideoRecordListener onVideoRecordListener) {
        this.mOnVideoRecordListener = onVideoRecordListener;
    }

    /**
     * 视频播放进度监听
     *
     * @param onPlayProgressListener
     */
    @Override
    public void setOnPlayProgressListener(@Nullable OnPlayProgressListener onPlayProgressListener) {
        this.mOnPlayProgressListener = onPlayProgressListener;
    }

    @Override
    public void setOnTalkListener(OnTalkListener onTalkListener) {
        this.mOnTalkListener = onTalkListener;
    }

    /**
     * 设备能力集回掉
     *
     * @param onCameraAbilityCallback
     */
    @Override
    public void setOnCameraAbilityCallback(@Nullable OnCameraAbilityCallback onCameraAbilityCallback) {
        this.mOnCameraAbilityCallback=onCameraAbilityCallback;
    }

    /**
     * 摄像头设置回掉
     *
     * @param onCameraSettingCallback
     */
    @Override
    public void setOnCameraSettingCallback(@Nullable OnCameraSettingCallback onCameraSettingCallback) {
        this.mOnCameraSettingCallback=onCameraSettingCallback;
    }

    /**
     * 切换清晰度
     * {@link ZPlayer#QUALITY_SD,ZPlayer#QUALITY_HD}
     *
     * @param quality
     */
    @Override
    public void switchPlayQuality(int quality) {

    }

    /**
     * 释放资源,注意请把所有setXXX的数据设置为空
     */
    @Override
    public void release() {
        mContext = null;
        mTextureView = null;
        mOnPlayListener = null;
        mPlayUrl = null;
        mMute = MUTE_DEF;
        mPlayState = STATE_IDLE;
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    @Override
    public boolean isPlaying() {
        return mPlayState == STATE_PLAYING;
    }

    @Override
    public boolean isStop() {
        return mPlayState==STATE_IDLE||mPlayState==STATE_ENDED;
    }

    @Override
    public boolean isPause() {
        return mPlayState == STATE_PAUSE;
    }

    /**
     * 获取播放状态
     *
     * @return
     */
    @Override
    public @State int getPlaySate() {
        return mPlayState;
    }

    /**
     * 截屏,结果在{@link #setOnCapturePictureListener(OnCapturePictureListener)}中回掉
     *
     * @param path 截屏成功后保存的路径
     */
    @Override
    public void capturePicture(@NonNull String path) {
        if (mTextureView != null) {
            Bitmap bitmap = mTextureView.getBitmap();
            if (bitmap != null) {
                ThreadUtils.getExecutorService().execute(() -> {
                    boolean success = BitmapUtils.keepBitmap(bitmap, 100, path);
                    ThreadUtils.runMainThread(() -> {
                        AppUtils.scannerFile(mContext, path);
                        if (mOnCapturePictureListener != null) {
                            mOnCapturePictureListener.onCapturePictureResult(success, path);
                        }
                    });
                });
            }
        } else {
            Logger.e(TAG, "capturePicture:mTextureView is null");
            ThreadUtils.runMainThread(() -> {
                if (mOnCapturePictureListener != null) {
                    mOnCapturePictureListener.onCapturePictureResult(false, path);
                }
            });
        }

    }

    @Nullable
    @Override
    public Bitmap capturePicture() {
        return mTextureView != null ? mTextureView.getBitmap() : null;
    }


    /**
     * 开启电子放大
     *
     * @param oRect
     * @param curRect
     */
    @Override
    public void openDigitalZoom(Rect oRect, Rect curRect) {

    }

    /**
     * 关闭电子放大
     */
    @Override
    public void closeDigitalZoom() {

    }

    @Override
    public long getCurrentTime() {
        return -1;
    }

    @Override
    public void setAutoGetAbility(boolean autoGetAbility) {
        this.mAutoGetAbility = autoGetAbility;
    }
    @Override
    public void setAutoGetSettings(boolean autoGetSettings) {
        this.mAutoGetSettings = autoGetSettings;
    }


    //###########下面定义公用方法################

    /**
     * 播放状态改变时调用
     *
     * @param status
     */
    protected void callStatusChange(@State int status) {
        mPlayState = status;
//        Log.d(TAG, "invokeStatusChange:" + Thread.currentThread().getName());
        if (mOnPlayListener != null) {
            ThreadUtils.runMainThread(() -> mOnPlayListener.onPlayStatusChange(status));
        }
    }

    /**
     * 播放错误时调用
     *
     * @param error
     */
    protected void callError(@PlayError.ErrorCode int code, String error) {
        Log.e(TAG, "playError:" + error);
        if (mOnPlayListener != null) {
            ThreadUtils.runMainThread(() -> mOnPlayListener.onPlayError(code, error));
        }
    }

    /**
     * 录制视频开始时调用
     */
    protected void callRecordVideoStart() {
        Log.d(TAG, "callRecordVideoStart:开始录像");
        if (mOnVideoRecordListener != null) {
            ThreadUtils.runMainThread(() -> mOnVideoRecordListener.onStartRecordVideo());
        }
    }

    /**
     * 录制视频结束时调用
     *
     * @param path
     */
    protected void callRecordVideoStop(String path) {
        Log.d(TAG, "callRecordVideoStop:结束录像");
        if (mOnVideoRecordListener != null) {
            ThreadUtils.runMainThread(() -> mOnVideoRecordListener.onStopRecordVideo(path));
        }
    }

    /**
     * 录制视频发生错误时调用
     *
     * @param error
     */
    protected void callRecordVideoError(String error) {
        Log.e(TAG, "callRecordVideoError:录制视频发生错误:" + error);
        if (mOnVideoRecordListener != null) {
            ThreadUtils.runMainThread(() -> mOnVideoRecordListener.onErrorRecordVideo(error));
        }
    }
    /**
     * 播放状态改变时调用
     *
     * @param status
     */
    protected void callTalking(@OnTalkListener.TalkStatus int status,String error) {
        if (mOnTalkListener != null) {
            ThreadUtils.runMainThread(() -> mOnTalkListener.onTalkCallback(status,error));
        }
    }


}
